import { i18n } from 'boot/i18n'
import { defineStore } from 'pinia'
import { colors, Dark, setCssVar } from 'quasar'
import quasarVariables from 'src/css/quasar.module.scss'
import { getStore, removeStore, setStore } from 'src/utils/storage'

const { luminosity } = colors
const initColors = quasarVariables || {}

// const dark = window.matchMedia('(prefers-color-scheme: dark)').matches

export const useSysSettingStore = defineStore('systemSetting', {
  state: () => ({
    primaryBG: getStore('primaryBG', 'L') || initColors.primary,
    positiveBG: getStore('positiveBG', 'L') || initColors.positive,
    negativeBG: getStore('negativeBG', 'L') || initColors.negative,
    infoBG: getStore('infoBG', 'L') || initColors.info,
    warningBG: getStore('warningBG', 'L') || initColors.warning,
    isDark: false, // getStore('isDark', 'L') ?? dark,
    isDense: getStore('isDense', 'L') ?? true,
    locale: i18n.locale.value // getStore('locale', 'L') || i18n.locale
  }),
  getters: {
    BgToColor: state => {
      return color => luminosity(state[color + 'BG']) <= 0.4 ? 'white' : 'dark'
    }
  },
  actions: {
    setColor (color, key) {
      setCssVar(key, color)
      key += 'BG'
      this[key] = color
      setStore(key, color, 'L')
    },

    setLocale (locale = this.locale) {
      this.locale = locale
      i18n.locale.value = locale
      setStore('locale', locale, 'L')
    },

    setInitColor () {
      for (const key in initColors) setCssVar(key, this[`${key}BG`])
    },

    setDark (isDark) {
      this.isDark = isDark
      this.toggleDark()
      setStore('isDark', isDark, 'L')
    },

    toggleDark () {
      Dark.set(this.isDark)
    },

    setDense (isDense) {
      this.isDense = isDense
      setStore('isDense', isDense, 'L')
    },

    resetSetting () {
      this.isDense = true
      removeStore('isDense', 'L')
      for (const key in initColors) {
        const formatKey = `${key}BG`
        this[formatKey] = initColors[key]
        removeStore(formatKey, 'L')
        setCssVar(key, initColors[key])
      }
    }
  }
})